package znet

import (
	"errors"
	"gitee.com/hufengjiu/go-zinx/ziface"
	"log"
	"sync"
)

type ConnManager struct {
	connections map[uint32]ziface.IConnection
	mu          sync.RWMutex
}

func (m *ConnManager) Add(conn ziface.IConnection) {
	m.mu.Lock()
	defer m.mu.Unlock()

	m.connections[conn.GetConnId()] = conn

	log.Printf("[Add] Conn id %d", conn.GetConnId())
}

func (m *ConnManager) Remove(conn ziface.IConnection) {
	m.mu.Lock()
	defer m.mu.Unlock()

	delete(m.connections, conn.GetConnId())
}

func (m *ConnManager) Get(connId uint32) (ziface.IConnection, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()

	conn, ok := m.connections[connId]
	if !ok {
		return nil, errors.New("Conn not found")
	}

	return conn, nil
}

func (m *ConnManager) Len() int {
	return len(m.connections)
}

// 清除并停止所有连接
func (m *ConnManager) ClearConn() {
	m.mu.Lock()
	defer m.mu.Unlock()

	for connId, conn := range m.connections {
		conn.Stop()
		delete(m.connections, connId)
	}

	log.Println("Clear all conn success!")
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
		mu:          sync.RWMutex{},
	}
}
